package View;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author kiko
 */
public class Editor extends javax.swing.JFrame {

    private String fileName;
    private String keyword;
    private Socket connection;
    
    /**
     * Creates new form Editor
     */
    public Editor(String fileName, String keyWord,Socket connection) {
        this.fileName = fileName;
        this.keyword = keyWord;
        this.connection = connection;
        initComponents();
        this.escreverTexto();
        this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jButtonSubmit = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jButtonSubmit.setText("Submit");
        jButtonSubmit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSubmitActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 297, Short.MAX_VALUE)
                        .addComponent(jButtonSubmit, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButtonSubmit)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonSubmitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSubmitActionPerformed
        try {
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.writeBytes("UPDT:" + keyword +"\n");
            ServerSocket welcome = new ServerSocket(50400);
            Socket aux = welcome.accept();
            sendFile(aux, fileName);
            aux.close();
            welcome.close();
            BufferedWriter bw = new BufferedWriter(new FileWriter("permissions" + File.separator + fileName));
            bw.write("read only");
            bw.close();
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(null, "Erro. Não foi possível salvar as alterações.");
            this.dispose();
        }
    }//GEN-LAST:event_jButtonSubmitActionPerformed

    public void sendFile(Socket conection, String fileName) {
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter("files" + File.separator + fileName));
            bw.write(jTextArea1.getText());
            bw.close();

            File file = new File("files" + File.separator + fileName);
            ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(conection.getOutputStream()));
            out.writeUTF(file.getName());
            out.writeLong(file.length());
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));

            byte[] buf = new byte[4096];
            while (true) {
                int len = in.read(buf);
                if (len == -1) {
                    break;
                }
                out.write(buf, 0, len);
                out.flush();
            }
            System.out.println("Arquivo enviado com sucesso");
            in.close();
            this.dispose();
        } catch (FileNotFoundException ex) {
            System.out.println("Erro: Arquivo não encontrado");
        } catch (IOException ex) {
            System.out.println("O AtendeCliente falhou ao tentar enviar o arquivo " + fileName);
        }
    }
    
    private void escreverTexto() {
        String linha;
        try {
            BufferedReader br = new BufferedReader(new FileReader("files" + File.separator + fileName));
            while (br.ready()) {
                linha = br.readLine();
                jTextArea1.append(linha + "\n");
            }
            br.close();
        } catch(IOException e) {
            JOptionPane.showMessageDialog(null, "Erro. Não foi possível abrir o arquivo especificado.");
            this.dispose();
        }
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonSubmit;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables
}
